<template>
  <div class="monthly-report-form">
    <div class="person">
      <el-form ref="postForm" :inline="true" :rules="rules" :model="formParam">
        <el-form-item label="账户：">
          <div>
            <i class="el-icon-user icon"></i>
            <span @click="handleDialogSelectUser" style="color: #409eff">{{
              selectedUser.username
            }}</span>
          </div>
        </el-form-item>
        <el-form-item label="汇报类型：">
          <el-select
            v-model="formParam.type"
            size="small"
            style="width: 134px"
            placeholder="请选择"
          >
            <el-option label="个人" value="person" />
            <el-option label="单位" value="unit" />
            <el-option label="战役/重点工作" value="keyWork" />
          </el-select>
        </el-form-item>
        <el-form-item label="年度：">
          <el-date-picker
            v-model="formParam.date"
            :clearable="false"
            type="year"
            size="small"
            format="yyyy年"
            style="width: 105px"
            placeholder="选择年"
          />
          <el-select
            v-model="formParam.dateType"
            size="small"
            style="width: 100px"
            placeholder="请选择"
          >
            <el-option label="上半年" value="上半年" />
            <el-option label="下半年" value="下半年" />
            <el-option label="全年" value="全年" />
          </el-select>
        </el-form-item>
        <el-form-item label="填报人：" prop="tbr">
          <el-input
            size="small"
            class="top-input"
            list="tbr"
            @input="handChangeTbr"
            v-model="formParam.tbr"
          />
          <datalist id="tbr">
            <option
              v-for="(item, index) in dataListForTbr"
              :value="item"
              :key="index"
            ></option>
          </datalist>
        </el-form-item>
        <el-form-item label="联系方式：" prop="tbrPhone">
          <el-input
            size="small"
            class="top-input"
            list="tbrPhone"
            @input="handChangePhone"
            v-model="formParam.tbrPhone"
          />
          <datalist id="tbrPhone">
            <option
              v-for="(item, index) in dataListForTbrPhone"
              :value="item"
              :key="index"
            ></option>
          </datalist>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :sm="24" :md="6" :lg="6" style="margin-bottom: 10px">
        <current-year-month-plan
          :selectedUserId="selectedUser.user"
          :date="formParam.date"
        />
      </el-col>
      <el-col :sm="24" :md="18">
        <el-card class="box-card">
          <div class="header">
            <h2>{{ tableTitle }}</h2>
            <div class="extra">
              <span></span>
              <span
                >填表日期：{{ parseTime(new Date(), "{y}年{m}月{d}日") }}</span
              >
            </div>
          </div>
          <yearly-report-table
            :dataSource="weeklyReportDatas"
            :reportType="formParam.type"
            :onAdd="handleAddRecord"
            :onDelete="handleDeleteRecord"
            :onSubmit="handleSaveRecord"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 选择领导 -->
    <el-dialog
      title="选择人员"
      :visible.sync="dialogSelectUser"
      append-to-body
      :modal="false"
      width="90%"
      style="margin-top: -6vh"
    >
      <user-manager
        :isRadio="true"
        :userOuter="false"
        :onSelectUsers="handSelectLeader"
        ref="userManager"
      />
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import _ from "lodash";
import moment from "moment";
import { uuid, parseTime } from "@/utils/index.js";
import { getYearReportName } from '../utils/plan'
import { createYearSchedule } from "@/api/plann";

export default {
  props: {
    weekRecords: {
      type: Array,
      default: () => [],
    },
    date: {
      type: String,
    },
    planType: {
      type: String,
    },
    onClose: {
      type: Function,
    },
  },
  computed: {
    ...mapGetters(["name", "id", "roles"]),
    tableTitle() {
      return getYearReportName(this.formParam)
    }
  },
  components: {
    YearlyReportTable: () => import("./YearlyReportTable.vue"),
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager.vue"),
    CurrentYearMonthPlan: () => import("./CurrentYearMonthPlan.vue")
  },
  watch: {
    weekRecords: {
      handler(records) {
        this.formParam = { ...this.formParam, tbr: "", tbrPhone: "" };
      },
      immediate: true,
    },
  },

  data() {
    return {
      formParam: {
        type: "person",
        date: new Date(),
        dateType: "上半年",
      },
      weeklyReportDatas: [this.initRecord()],
      dialogSelectUser: false,
      selectedUser: {},
      dataListForTbrPhone: [],
      dataListForTbr: [],
      rules: {
        tbr: [
          { required: true, message: "请输入填报人姓名", trigger: "change" },
        ],
        tbrPhone: [
          {
            required: true,
            message: "请输入填报人联系电话",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.dataListForTbrPhone = JSON.parse(
      localStorage.getItem("dataListForTbrPhone")
    );
    this.dataListForTbr = JSON.parse(localStorage.getItem("dataListForTbr"));
    this.selectedUser = {
      username: this.name && this.name.split("(")[0],
      user: this.id,
    };
  },
  methods: {
    handChangeTbr() {
      this.dataListForTbr = JSON.parse(localStorage.getItem("dataListForTbr"));
    },
    handChangePhone() {
      this.dataListForTbrPhone = JSON.parse(
        localStorage.getItem("dataListForTbrPhone")
      );
    },
    parseTime,
    initRecord() {
      return {
        tempID: "new" + uuid(),
        content_1: "",
        content_2: "",
        content_3: "",
        content_4: "",
      };
    },
    handSelectLeader(users) {
      if (!users.length) {
        this.$message.info("请选择处理人");
        return;
      }
      const { first_name, id } = users[0];

      this.selectedUser = { username: first_name, user: id };
      this.dialogSelectUser = false;
    },

    handleAddRecord() {
      this.weeklyReportDatas.push(this.initRecord());
    },
    handleDeleteRecord(selectedRows) {
      const rowsId = selectedRows.map((item) => item.tempID);
      const filterList = this.weeklyReportDatas.filter(
        (item) => !rowsId.includes(item.tempID)
      );
      this.weeklyReportDatas = filterList.length
        ? filterList
        : [this.initRecord()];
    },
    /*
     * 缓存输入框记录
     * param: String; 对象字段名称
     */
    saveInputSessionForDataListForTbr(param) {
      const value = param;
      if (!value) return;
      var locData = JSON.parse(localStorage.getItem("dataListForTbr"));
      if (!locData || !locData.includes(value)) {
        if (!locData) {
          localStorage.setItem("dataListForTbr", JSON.stringify([value]));
        } else {
          if (locData.length > 4) {
            locData = locData.slice(locData.length - 4, locData.length);
          }
          localStorage.setItem(
            "dataListForTbr",
            JSON.stringify(locData.concat([value]))
          );
        }
      }
    },
    /*
     * 缓存输入框记录
     * param: String; 对象字段名称
     */
    saveInputSessionForDataListForTbrPhone(param) {
      const value = param;
      if (!value) return;
      var locData = JSON.parse(localStorage.getItem("dataListForTbrPhone"));
      if (!locData || !locData.includes(value)) {
        if (!locData) {
          localStorage.setItem("dataListForTbrPhone", JSON.stringify([value]));
        } else {
          if (locData.length > 4) {
            locData = locData.slice(locData.length - 4, locData.length);
          }
          localStorage.setItem(
            "dataListForTbrPhone",
            JSON.stringify(locData.concat([value]))
          );
        }
      }
    },
    handleSaveRecord: _.debounce(async function () {
      console.log('ccccccc')
      this.$refs["postForm"].validate((valid) => {
        if (valid) {
          const { type, date, dateType, tbr, tbrPhone } = this.formParam;
          this.saveInputSessionForDataListForTbr(tbr);
          this.saveInputSessionForDataListForTbrPhone(tbrPhone);
          
          const { user } = this.selectedUser;
          let newRows = [...this.weeklyReportDatas];
          // 如果是个人填报 删除表格第四列内容
          if (this.formParam.type !== "keyWork") {
            newRows = [...this.weeklyReportDatas].map((item) => {
              const { content_4, ...reset } = item;
              return reset;
            });
          }
          
          //总字数不能超过1000
          let length = 0
          let contentIsEmpty = false
          newRows.forEach(e =>{
            for(let key in e){
              if(key == 'tempID') continue
              if(e[key] == ''){
                contentIsEmpty = true
              }
              length = length + e[key].replace(/\s*/g,"").length
            }
          })
          if(contentIsEmpty){
            this.$message.warning("内容不能为空！")
            return
          }
          //标题大概占40个字数 1000-40
          if(length > 960){
            this.$message.warning("总字数不允许超过1000")
            return
          }
          // 将数据内容转化为目标格式
          const _newRows = newRows.map((row) => {
            return {
              ...row,
              type,
              user,
              year: moment(date).year(),
              date_type: dateType,
              tbr,
              tbr_phone: tbrPhone,
            };
          });
          createYearSchedule(_newRows).then((res) => {
            if (res && res.data) {
              this.$message.success("保存成功");
              this.onClose();
              this.weeklyReportDatas = [this.initRecord()];
            }
          });
        }
      });
    }, 300),
    handleDialogSelectUser() {
      if (this.roles.some((role) => ~role.indexOf("管理员"))) {
        this.dialogSelectUser = true;
      }
    },
  },
};
</script>
<style lang="scss">
.monthly-report-form {
  margin-top: -20px;
  .person {
    margin-bottom: 20px;
    line-height: 20px;
    font-size: 13px;
    color: #232323;
    cursor: pointer;

    .icon {
      font-size: 18px;
      color: #409eff;
    }
    .top-input {
      width: 200px;
      input {
        height: 26px;
        padding-right: 0 !important;
        line-height: 14px;
      }
    }
    .importBtn {
      float: right;
      margin-top: 5px;
      font-size: 12px;
      color: #409eff;
      cursor: pointer;
    }
  }
  .box-card {
    margin-bottom: 20px;
    .header {
      h2 {
        text-align: center;
        color: #666;
      }
      .extra {
        margin-top: 34px;
        padding: 0 40px 4px 13px;
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
        font-size: 14px;
        color: #666;
      }
    }
  }
  @media screen and (max-width: 500px) {
    .box-card {
      .el-card__body {
        padding: 20px 10px;
      }
    }
    .person {
      div:last-child {
        display: block !important;
        margin-top: 4px;
        span {
          margin-left: 0px !important;
          display: block;
          div {
            display: inline-block !important;
          }
        }
        span:last-child {
          margin-top: 4px;
        }
      }
    }
  }
}
</style>
